Page({
  data: {
    identity: '',
    age: '',
    ratingQuestions: [
      '餐食口味是否符合预期？',
      '食材新鲜度如何？',
      '饭菜分量是否充足？',
      '送餐服务是否及时？',
      '餐食卫生状况如何？',
      '整体膳食满意度如何？'
    ],
    ratings: {},
    addid:{},
    improvementSuggestion: '',
    improvementSuggestions: '',
    anonymousL: 0,
  },

  onIdentityChange(e) {
    this.setData({
      identity: e.detail.value
    });
  },
  onLoad(options) {
    console.log(options)
    this.setData({
      addid:options
    })
  },
  onAgeChange(e) {
    this.setData({
      age: e.detail.value
    });
  },

  onRatingChange(e) {
    const questionIndex = e.currentTarget.dataset.index;
    const rating = e.detail.value;
    const ratings = this.data.ratings;
    ratings[questionIndex] = rating;
    this.setData({
      ratings
    });
  },

  onImprovementSuggestionChanges(e) {
    this.setData({
      improvementSuggestions: e.detail.value
    });
  },

  onImprovementSuggestionChange(e) {
    this.setData({
      improvementSuggestion: e.detail.value
    });
  },
  onAnonymousChange(e) {
    console.log(e.detail.value)
  },
  submitSurvey() {
    const {
      identity,
      age,
      ratings,
      improvementSuggestion,
      improvementSuggestions,
      addid
    } = this.data;
    
    console.log('addid 的值为:', addid);
    // 校验基本信息
    if (!identity) {
      wx.showToast({
        title: '请选择您的身份',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (!age) {
      wx.showToast({
        title: '请选择您的年龄',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    // 校验满意度评分
    let totalScore = 0;
    const ratingArray = [];
    const ratingQuestions = this.data.ratingQuestions;
    for (let i = 0; i < ratingQuestions.length; i++) {
      const rating = Number(ratings[i]);
      if (isNaN(rating)) {
        wx.showToast({
          title: '请完成所有满意度评分',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      ratingArray.push(rating);
      totalScore += rating;
    }

    // 校验开放式问题
    if (!improvementSuggestions.trim()) {
      wx.showToast({
        title: '请填写对营养膳食的改进建议',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (!improvementSuggestion.trim()) {
      wx.showToast({
        title: '请填写您对最满意的一道餐品及原因',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    const userInfo = wx.getStorageSync('userInfo');
    const imageUrl = userInfo.avatarUrl;
    const wxUserId = userInfo.wxUserId;
    const anonymousL = this.data.anonymousL
    // 所有校验通过，提交问卷（这里只是模拟打印数据，实际需发送到服务器）
    console.log('身份:', identity);
    console.log('年龄:', age);
    console.log('满意度评分:', ratingArray);
    console.log('改进建议:', improvementSuggestion);
    console.log('原因:', improvementSuggestions);
    const data = {
      crole: identity,
      orderId: addid.id,
      productId: addid.productId,
      userId: Number(wxUserId),
      rating: ratingArray[5],
      score1: ratingArray[0],
      score2: ratingArray[1],
      score3: ratingArray[2],
      score4: ratingArray[3],
      score5: ratingArray[4],
      cage: age,
      recommended: 0,
      // orderStatus: 4,
      content: improvementSuggestion,
      dishsuggest: improvementSuggestions,
      imageUrl: imageUrl,
      anonymousL: anonymousL
    };
    wx.request({
      url: `https://199shq.com/api/wxComment/addComment`,
      method: 'POST',
      data: data,
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.state == 20000) {
          wx.showToast({
            title: '问卷提交成功',
            icon: 'success',
            duration: 2000
          });
          // 在需要返回上一页的地方调用该方法
          wx.navigateBack({
            delta: 2// 返回到页面栈的第一个页面
          });
        } else {
          wx.showToast({
            title: '问卷提交失败',
            icon: 'error',
            duration: 2000
          });
        }
      },
      fail: function (err) {
        console.log('请求接口失败:', err);
      }
    });

  }
});